package com.zjw.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjw.domain.dto.EditPasswordDto;
import com.zjw.domain.dto.EditUserDto;
import com.zjw.domain.dto.LoginRegisterUserDto;
import com.zjw.domain.entity.User;
import com.zjw.domain.vo.LoginSuccessVo;
import com.zjw.domain.vo.ResponseResult;
import com.zjw.domain.vo.UserInfoVo;
import com.zjw.domain.vo.UsernameAvatarVo;
import com.zjw.exception.SystemException;
import com.zjw.mapper.UserMapper;
import com.zjw.service.UserService;
import com.zjw.system.SystemReturnEnum;
import com.zjw.utils.BeanCopyUtil;
import com.zjw.utils.JWTUtil;
import org.springframework.stereotype.Service;

/**
 * 用户信息表(User)表服务实现类
 *
 * @author lkzy
 * @since 2023-12-29 23:49:31
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public ResponseResult login(String username, String password) {
//        数据库中查询用户名对象
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);

        User user = getOne(wrapper);
//        比对密码
//        使用MD5加密比对
        if (user == null || !user.getPassword().equals(SecureUtil.md5(password)))
            return ResponseResult.error(SystemReturnEnum.USER_INFO_ERROR);

//        正确则颁发JWT
        return ResponseResult.ok(new LoginSuccessVo(JWTUtil.creatJWT(user.getId().toString())));
    }

    @Override
    public ResponseResult register(LoginRegisterUserDto user) {

//        查询用户名是否已经存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());

        if (getOne(wrapper) != null) {
            return ResponseResult.error(SystemReturnEnum.USER_EXISTED);
        }

//       密码经过加密后插入
        user.setPassword(SecureUtil.md5(user.getPassword()));
//        创建用户
        User resUser = BeanCopyUtil.copyBean(user, User.class);
        resUser.setAge(18);
        resUser.setSex("保密");
        resUser.setRole("user");
        save(resUser);
        return ResponseResult.ok();
    }

    @Override
    public ResponseResult getUsernameAvatar(Long jwtId) {

        User user = getById(jwtId);
        if (user == null) {
            return ResponseResult.error(SystemReturnEnum.DATA_INVALID);
        }

        UsernameAvatarVo res = BeanCopyUtil.copyBean(user, UsernameAvatarVo.class);


        return ResponseResult.ok(res);
    }

    @Override
    public ResponseResult getUserInfo(Long jwtId) {
        User user = getById(jwtId);
        if (user == null) {
            return ResponseResult.error(SystemReturnEnum.DATA_INVALID);
        }

        UserInfoVo res = BeanCopyUtil.copyBean(user, UserInfoVo.class);

        return ResponseResult.ok(res);

    }

    /**
     * 更新用户信息
     *
     * @param jwtId       jwt id
     * @param editUserDto 编辑用户dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult editUser(Long jwtId, EditUserDto editUserDto) {


        User user = BeanCopyUtil.copyBean(editUserDto, User.class);
        user.setId(jwtId);

//        判断用户名是否可用
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, editUserDto.getUsername());
        User temp = getOne(wrapper);

        if (temp != null && !temp.getId().equals(jwtId)) {
//            不为空却不是当前用户则说明已经存在
            throw new SystemException(SystemReturnEnum.USER_EXISTED);
        }

        updateById(user);

        return ResponseResult.ok();
    }

    /**
     * 更新密码
     *
     * @param jwtId           jwt id
     * @param editPasswordDto 编辑密码dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult editPassword(Long jwtId, EditPasswordDto editPasswordDto) {
//        MD5加密
        editPasswordDto.setNewPassword(SecureUtil.md5(editPasswordDto.getNewPassword()));
        editPasswordDto.setOldPassword(SecureUtil.md5(editPasswordDto.getOldPassword()));

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId, jwtId);
        User user = getOne(wrapper);
        if(!user.getPassword().equals(editPasswordDto.getOldPassword()))
            throw new SystemException(SystemReturnEnum.OLD_PASSWORD_ERROR);

        user.setPassword(editPasswordDto.getNewPassword());
        updateById(user);
        return ResponseResult.ok();
    }

    @Override
    public void updateAvatar(Long jwtId, String resPath) {
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getId, jwtId).set(User::getAvatar, resPath);
        System.out.println(update(wrapper));
    }

    /**
     * 按id获取用户名
     *
     * @param createBy 创建者
     * @return {@link String}
     */
    @Override
    public String getUserNameById(Long createBy) {
        User user = getById(createBy);
        return user.getUsername();
    }

    @Override
    public String getUserAvatarById(Long temp) {
        User user = getById(temp);
        return user.getAvatar();
    }
}

